<?php
require_once ( "filesys.php" );

class ajax_module
{
	function ajax_module ( & $dbm, $base_dir = "ajax", $layman = null )
	{
		$this->dbm      = & $dbm;
		$this->base_dir = $base_dir;
		$this->layman   = & $layman;

		// Names to be used to retrieve data directly from the $REQUEST
		$this->module_field = "module";
		$this->action_field = "action";
		
		// see util_ff ()
		$this->form_mode    = "PG";

		$this->last_error   = '';
	}

	function & exec ( $module = false, $action = false, $all_params = null )
	{
		global $sess;

		if ( ! $module ) $module = util_ff ( $this->module_field, $this->form_mode );
		if ( ! $action ) $action = util_ff ( $this->action_field, $this->form_mode );

		$subm = "";

		if ( $module ) 
		{
			$vals = explode ( ".", $module );
	
			$module = $vals [ 0 ];

			if ( sizeof ( $vals ) > 1 ) $subm = $vals [ 1 ];
		} else if ( $action ) {
			$vals = explode ( ".", $action );

			$module = @ $vals [ 0 ];
			$subm   = @ $vals [ 1 ];
			$action = @ $vals [ 2 ];

			if ( $subm && ( ! $action ) )
			{
				$action = $subm;
				$subm   = false;
			}
		}

		$res = null;

		$fname = $this->resolve_addr ( $module, $subm, $this->base_dir == 'ajax' );

		error_log ( "FNAME: $fname - module: $module - action: $action" );
	
		if ( ! $fname ) 
		{
			$this->last_error = "Module not found: \"$module\" - fname: \"$fname\"";
			return $res;
		}

		if ( include_once ( $fname ) )
		{
			if ( $all_params )
				$args = & $all_params;
			else
				$args = Array ( $module, $action );

			// error_log ( "CLASS: $module" );

			if ( $this->base_dir == 'modules' )
				eval ( "\$obj = new base_$module ();" );
			else
				eval ( "\$obj = new $module ();" );
			// error_log ( "OBJ: " . $obj->name );
			$obj->class_init ( & $sess, & $this->dbm, & $this->layman );

			// print_r ( $this->layman->js );

			$res = & $obj->invoke ( & $obj, & $args );

			if ( ! $res ) $this->last_error = "Method: \"$action\" on module: \"$module\" did not return any value.";
			
		} else
			$this->last_error = "Error in including module: $module - fname: $fname";

		return $res;
	}

	function resolve_addr ( $module, $subm, $is_ajax )
	{
		if ( ! $is_ajax )
		{
			if ( filesys_exists ( "modules/$module/{$module}.php" ) ) return "modules/$module/{$module}.php";
			if ( filesys_exists ( "modules/{$module}.php" ) ) return "modules/{$module}.php";
		} else {
			if ( ! $subm )
			{
				if ( filesys_exists ( "modules/$module/ajax/{$module}.php" ) ) return "modules/$module/ajax/{$module}.php";
				if ( filesys_exists ( "ajax/{$module}.php" ) ) return "ajax/{$module}.php";
			} else {
				if ( filesys_exists ( "modules/$module/ajax/{$subm}.php" ) ) return "modules/$module/ajax/{$subm}.php";
				if ( filesys_exists ( "ajax/{$subm}.php" ) ) return "ajax/{$subm}.php";
			}
		}

		return '';
	}
}
?>
